import { createRouter, createWebHistory } from 'vue-router'

// 路由配置
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/homestay/:id',
    name: 'HomestayDetail',
    component: () => import('../views/HomestayDetail.vue')
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('../views/Search.vue')
  },
  {
    path: '/news',
    name: 'News',
    component: () => import('../views/News.vue')
  },
  {
    path: '/news/:id',
    name: 'NewsDetail',
    component: () => import('../views/NewsDetail.vue')
  },
  {
    path: '/user',
    name: 'UserCenter',
    component: () => import('../views/UserCenter.vue'),
    children: [
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('../views/UserProfile.vue')
      },
      {
        path: 'bookings',
        name: 'UserBookings',
        component: () => import('../views/UserBookings.vue')
      },
      {
        path: 'favorites',
        name: 'UserFavorites',
        component: () => import('../views/UserFavorites.vue')
      }
    ]
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  
  // 需要登录的路由
  const authRoutes = ['/user']
  
  // 如果访问需要登录的页面但未登录，则重定向到登录页
  if (authRoutes.some(path => to.path.startsWith(path)) && !isAuthenticated) {
    next({ name: 'Login' })
  } else {
    next()
  }
})

export default router 